package com.hsd.voice_asr.listener;


import com.hsd.voice_asr.properties.AliAsrProperties;
import com.hsd.voice_asr.socket.TCPControlServer;
import com.hsd.voice_asr.socket.TCPStreamServer;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class ServletListener implements ServletContextListener {

    private TCPStreamServer tcpServer;

    private TCPControlServer tcpControlServer;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext application = sce.getServletContext();
        WebApplicationContext appctx = WebApplicationContextUtils.getWebApplicationContext(application);
        AliAsrProperties aliAsrProperties = appctx.getBean(AliAsrProperties.class);
        tcpServer = new TCPStreamServer(aliAsrProperties);
        tcpServer.setDaemon(true);
        tcpServer.start();
        tcpControlServer = new TCPControlServer();
        tcpControlServer.setDaemon(true);
        tcpControlServer.start();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        tcpServer.flag = false;
        tcpControlServer.flag = false;
    }
}
